import moment from "moment"
import fsExtra from "fs-extra"
import { DownloaderHelper } from "node-downloader-helper"

const DIR = "./output"
const Cookie = `sp=3537ed08-7d8b-487f-bce8-ce11602d95a3; xp_session_identifier=ts80x1mns7m; _currentH=d3d3LnN0cmF2YS5jb20=; _sp_ses.047d=*; _strava4_session=e9dsi3okiud07670fgrphm8m2e85dr3a; _sp_id.047d=c725583e-6eb1-4b94-8ae4-200d84d3222a.1745910262.4.1763955975.1754381224.7fd475de-0a4a-4b72-820f-9c4683fb6eb8`
const Token = `DCImlDVQv_w-5-_DzJVY8PX1iR7DmEUyCd4MUUC61oaxbowKCK9VzVeJq5SSH5hF7asU3OQ2ShuDbKM6Nci0bg`
// const DIR = "./mj_output"
// const Cookie = `sp=3537ed08-7d8b-487f-bce8-ce11602d95a3; _ga=GA1.1.1206643251.1730691606; _tt_enable_cookie=1; _scid=GTb2_GiNcR2DibpKlQDcvBZLsnZqDe31; _strava_cbv3=true; xp_session_identifier=ts80x1mns7m; _ttp=xrMNyiTkzLLImu5vbcfI0FWOQz4.tt.1; _currentH=d3d3LnN0cmF2YS5jb20=; _gcl_au=1.1.1922007201.1753957368; _sp_ses.047d=*; _fbp=fb.1.1753957369045.571117150975870679; _ScCbts=%5B%5D; _sctr=1%7C1753891200000; _strava4_session=7agfsip23lifr7v3pp75ihmch3p8lsct; ttcsid=1753957376658::g67AAy_fM4uR8xHNaCuw.2.1753957493444; ttcsid_CRCAPDJC77UE5B95LUQG=1753957376658::uQQrBLBbCQarY0goMCrD.2.1753957494215; _ga_12345=GS2.1.s1753957370$o2$g0$t1753957584$j60$l0$h1691228487; _sp_id.047d=c725583e-6eb1-4b94-8ae4-200d84d3222a.1745910262.2.1753957594.1745910883.2082af0d-e182-447c-9b64-dd9ae124ec95; _ga_ESZ0QKJW56=GS2.1.s1753957368$o2$g1$t1753957594$j50$l0$h0; _scid_r=Jrb2_GiNcR2DibpKlQDcvBZLsnZqDe31UPjp_w`
// const Token = `ETDpzUplPa-Rd52AOnTGb9rTXpQTsnxFPxr_Zcymg0hmlcU8pqqDF8IVPjmG04Vl7LkFH2GZYFUhoJxSiSPthA`

const fetchActivity = async () => {
  try {
    const response = await fetch(
      "https://www.strava.com/athletes/151089784/relative_effort?num_weeks=12",
      // "https://www.strava.com/athletes/166174957/relative_effort?num_weeks=12",
      {
        headers: {
          accept: "application/json, text/plain, */*",
          "accept-language": "en-US",
          "cache-control": "no-cache",
          pragma: "no-cache",
          priority: "u=1, i",
          "sec-ch-ua":
            '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
          "sec-ch-ua-mobile": "?0",
          "sec-ch-ua-platform": '"macOS"',
          "sec-fetch-dest": "empty",
          "sec-fetch-mode": "cors",
          "sec-fetch-site": "same-origin",
          "x-csrf-token": Token,
          "x-requested-with": "XMLHttpRequest",
          cookie: Cookie,
          Referer: "https://www.strava.com/dashboard",
          "Referrer-Policy": "strict-origin-when-cross-origin",
        },
        body: null,
        method: "GET",
      }
    )

    const data = await response.json()

    let activities = data.weekly_scores.reduce((last, current) => {
      return last.concat(current.activities)
    }, [])

    activities = activities.filter(
      (activity) => activity.activity_type === "Ride"
    )

    return activities
  } catch (error) {
    console.error(error)
  }
}

const downloadFile = async (url, fileInfo) => {
  console.log(`Downloading`, url)

  const dl = new DownloaderHelper(url, DIR, {
    headers: {
      "x-csrf-token": Token,
      cookie: Cookie,
      Referer: "https://www.strava.com/dashboard",
    },
  })

  dl.on("end", ({ fileName }) => {
    const rename = `${DIR}/${moment(fileInfo.start_date).format(
      "YYYY-MM-DD"
    )}.${moment(fileInfo.start_date).format("x")}.fit`

    fsExtra.rename(`${DIR}/${fileName}`, rename)

    console.log(`downloaded file: ${rename}`)
  })
  dl.start()
}

const updateFilesAfterLastDate = async (lastDate) => {
  const activities = await fetchActivity()
  console.log(activities)

  const updateList = activities.filter((activity) => {
    return moment(activity.start_date).format("x") > lastDate
  })

  return updateList
}

const findLastestActivity = async () => {
  let files = fsExtra.readdirSync(DIR)

  files = files
    .filter((file) => file.includes(".fit"))
    .map((file) => file.split(".")[1])
    .sort((a, b) => Number(b) - Number(a))

  return Number(files[0])
}

const asyncStravaRideActivity = async () => {
  // console.log(process.env.startTime);
  // return
  await fsExtra.ensureDir(DIR)

  const lastDate = await findLastestActivity()
  console.log(lastDate)

  const activities = await updateFilesAfterLastDate(lastDate)

  activities.forEach((activity) => {
    downloadFile(
      `https://www.strava.com/activities/${activity.id}/export_original`,
      activity
    )
  })
}

asyncStravaRideActivity()
